package com.mo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {

    public static void main(String[] args) throws IOException {
        List<SocketChannel> channelList = new ArrayList<>();
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.socket().bind(new InetSocketAddress(9000));
        //非阻塞IO
        channel.configureBlocking(false);
        System.out.println("服务启动成功！");

        while (true) {
            SocketChannel accept = channel.accept();
            if (accept != null) {
                System.out.println("连接成功！");
                accept.configureBlocking(false);
                channelList.add(accept);
            }
            //读取数据
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel sc = iterator.next();
                ByteBuffer buffer = ByteBuffer.allocate(128);
                int len = sc.read(buffer);
                if (len > 0) {
                    System.out.println(new String(buffer.array()));
                } else if (len == -1) {
                    iterator.remove();
                    System.out.println("客户端断开链接");
                }

            }
        }
    }
}
